const fs = require("fs");
const path = require("path");
const fullPath = path.join(__dirname,'./info.json')
// console.log(fullPath);
const data = fs.readFileSync(fullPath, 'utf8')
// console.log(data);
const newData = JSON.parse(data)
console.log(newData);


// 随机获取
function getRondem () {
// console.log(data);
const stochastic = Math.floor(Math.random()*(newData.length+1))
console.log(newData);
// console.log(Adata[stochastic]);
newData[stochastic].count++
fs.writeFileSync(fullPath,JSON.stringify(newData))
return newData[stochastic]
}

// console.log(getRondem());


// 1. 导入 http 模块
const http = require('http')

// 2. 创建 web 服务器实例
const server = http.createServer()

// 3. 启动服务器
server.listen(8888, () => {
  console.log('my server start work')
})

// 4. 为服务器实例绑定 request 事件，监听客户端的请求
server.on('request', (req, res) => {
  // 设置响应的内容为JSON
 res.setHeader('Content-Type', 'application/json; charset=utf-8')
  // 不能直接响应 对象/数组 需要转为字符串
   // 设置响应头信息
   res.setHeader("Access-Control-Allow-Origin", "*");
  const url = req.url;
  const mothod = req.method;
if (mothod === 'GET' &&  url === '/api/students' ) {
  res.end(JSON.stringify(newData))
}else if (mothod === 'GET' && url === '/api/getRondem') {
 res.end(JSON.stringify(getRondem()))
}
})